package com.mavenq.fly.aspect;

import com.mavenq.fly.annotation.Retry;
import com.mavenq.fly.commons.exception.BusinessException;
import lombok.extern.java.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * 重试切面
 *
 */
@Component
@Aspect
@Log
public class RetryAspect {

    @Pointcut("@annotation(com.mavenq.fly.annotation.Retry)")
    private void retryMethod() {
    }

    @Around("retryMethod()")
    public void retry(ProceedingJoinPoint point) {

        Retry retry = ((MethodSignature) point.getSignature()).getMethod().getAnnotation(Retry.class);
        int retryTimes = retry.retryTime();
        long retryPeriod = retry.retryPeriod();
        for (int retryTime = 0; retryTime < retryTimes; retryTime++) {
            try {
                point.proceed();
                return;
            } catch (Throwable throwable) {
                log.warning(throwable.getMessage());
                if(retryTime < retryTimes - 1){
                    try {
                        Thread.sleep(retryPeriod);
                    } catch (Exception e2) {
                        // nothing
                    }
                    continue;
                }
                throw new BusinessException(500, "重试异常");
            }
        }

    }

}
